#include <head.h>


int  my_tree(char * file_name)
{
//file_name 目录名称
    DIR *dir = opendir(file_name);

//f判断目录能否正常打开
    if (dir == NULL) {
        perror("无法打开目录");
        return 1;
    }



// 操作文件
    struct dirent *entry;

//文件名称
    const char * file;

//文件
    struct stat file_stat;

//拼接文件路径
    char file_path[1024];
  

//readdir 读取目录中的每一个文件 
    while ( (entry = readdir(dir)) != NULL)
    {
        //如果这个文件是目录 且不是  ”.“   或者”..“  则进入递归
        if (entry->d_type==DT_DIR  && strcmp(entry->d_name,"..") && strcmp(entry->d_name,".") )
        {
		//将文件路径拼接完整
            snprintf(file_path,sizeof(file_path),"%s/%s",file_name,entry->d_name);
            // printf("进入下一级目录file_path=%s\n",file_path);
            my_tree(file_path);
        }
        // printf("entry->d_name=%s\n",entry->d_name);
       
	//将文件路径拼接完整
        snprintf(file_path,sizeof(file_path),"%s/%s",file_name,entry->d_name);
        // printf("file_path=%s\n",file_path);
	//获得完整的文件名称
        file =file_path;
        
        int num = stat(file,&file_stat);
        if (num == -1)
        {
            perror("stat");
            return -1;
        }
        switch (file_stat.st_mode  & S_IFMT  )
        {
        case S_IFREG:
            printf("-");
            break;
        case S_IFDIR:
            printf("d");
            break;
        case S_IFCHR:
            printf("c");
            break;
        case S_IFBLK:
            printf("b");
            break;

        case S_IFIFO:
            printf("p");
            break;

        case S_IFSOCK:
            printf("s");
            break;
        case S_IFLNK:
            printf("l");
            break;   
        default:
            printf("未知文件类型");
            break;
        }


        printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
        printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
        printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");

        printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
        printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
        printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");

        printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
        printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
        printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");
        printf(" %lu ",file_stat.st_nlink );
        struct passwd * user= getpwuid(file_stat.st_uid);
        printf(" %s ",user->pw_name );
        struct group *  user_group = getgrgid(file_stat.st_gid);
        printf(" %s ",user_group->gr_name );
        printf(" %ld\t ",file_stat.st_size );
        time_t t=file_stat.st_atime;
        struct tm *local_time = localtime(&t);
        printf(" %d月 %d %d:%d \t", local_time->tm_mon+1,local_time->tm_mday,local_time->tm_hour, local_time->tm_min);
        printf(" %s \n",file);
    
    }
    
}

int main(int argc, char const *argv[])
{ 
    my_tree("../0820"); 
    return 0;
}
